
const { app, BrowserWindow, screen, session, Tray, Menu, dialog, shell } = require('electron');
const path = require('path')

const EnvContext = require('../../../common/context/EnvContext');
const fileUtil = require('../../../common/utils/fileUtil');

const { envConst } = require('../../../common/constans/envConstans');


exports.createTray = function (plugin) {
    doCreateTray(plugin)
    doCreateTrayWin(plugin)

}


function doCreateTray(plugin) {
    const pluginId = plugin.pluginId

    const theTray = EnvContext.getInstance().getTray(pluginId)
    if (theTray) {
        if (!theTray.isDestroyed()) {
            return
        }
    }

    let iconPath = plugin.pluginInfo.pluginSetting.traySetting.icon
    iconPath = path.join(fileUtil.getPluginPathByPluginId(pluginId), iconPath)

    const homepage = plugin.pluginInfo.homepage
    const name = plugin.pluginInfo.name
    const description = plugin.pluginInfo.description
    const version = plugin.pluginInfo.version
    const author = plugin.pluginInfo.author


    let tray = new Tray(iconPath)
    const contextMenu = Menu.buildFromTemplate([
        {
            label: "帮助文档",
            click: () => {
                process.nextTick(() => {
                    if (homepage.startsWith("http")) {
                        shell.openExternal(homepage);
                    }
                });
            },
        },
        {
            label: "重启",
            click() {
                // todo 重启tray应用
                doCreateTray(plugin)
            },
        },
        {
            label: "置顶",
            type: "checkbox",
            checked: "false",
            click() {
                // todo 置顶后，不受收缩托盘控制
            },
        },
        {
            label: "关于",
            click() {
                dialog.showMessageBox({
                    icon: iconPath,
                    title: name,
                    message: description,
                    detail: `Version: ${version}\nAuthor: ${author}`,
                });
            },
        },
        {
            role: "关于",
            label: "退出",
        },
    ]);
    tray.on("click", function () {
        let theWin = EnvContext.getInstance().getTrayWindow(pluginId)
        if (theWin) {
            if (!theWin.isDestroyed()) {
                if (theWin.isVisible()) {
                    theWin.hide()
                } else {
                    moveTrayWin(theWin, tray.getBounds())
                    theWin.show()
                }

            }
            else {
                // todo 窗口已被销毁，需要重新创建
            }
        }
    })

    tray.on("right-click", function () {
        let theWin = EnvContext.getInstance().getTrayWindow(pluginId)
        if (theWin) {
            if (!theWin.isDestroyed()) {
                if (theWin.isVisible()) {
                    theWin.hide()
                }
            }
        }
        tray.popUpContextMenu(contextMenu)
    })
    EnvContext.getInstance().setTray(pluginId, tray)
}



function moveTrayWin(win, bounds) {
    const theRect = screen.getDisplayMatching(bounds).workArea
    let winSizeWidth = win.getSize()[0]
    let winSizeHigth = win.getSize()[1]

    if (winSizeWidth > 350) {
        winSizeWidth = 350
    }
    if (winSizeHigth > 800) {
        winSizeHigth = 800
    }
    let x = bounds.x - winSizeWidth / 2 + bounds.width / 2
    let y = theRect.y
    win.setPosition(x, y)
    win.setSize(winSizeWidth, winSizeHigth)
}


function doCreateTrayWin(plugin) {
    const winId = plugin.pluginId
    const theWin = EnvContext.getInstance().getTrayWindow(winId)
    if (theWin) {
        return
    }

    let mainHtml = plugin.pluginInfo.pluginSetting.traySetting.main
    let preload = plugin.pluginInfo.preload
    preload = preload ? path.join(fileUtil.getPluginPathByPluginId(plugin.pluginId), preload) : null
    mainHtml = mainHtml ? path.join(fileUtil.getPluginPathByPluginId(plugin.pluginId), mainHtml) : null

    if (envConst.dev) {
        preload = plugin.pluginInfo.development.preload
        mainHtml = plugin.pluginInfo.development.tray
    }

    const windowOptions = {
        width: plugin.pluginInfo.pluginSetting.width,
        height: plugin.pluginInfo.pluginSetting.height,
        maxWidth: plugin.pluginInfo.pluginSetting.maxWidth,
        minWidth: plugin.pluginInfo.pluginSetting.minWidth,
        frame: false,
        show: false,
        transparent: true,
        skipTaskbar: true,
        useContentSize: true,
        autoHideMenuBar: true,
        webPreferences: {
            // devTools: false,
            spellcheck: false,
            webSecurity: false,
            enableRemoteModule: true,
            backgroundThrottling: false,
            contextIsolation: true,
            webviewTag: true,
            nodeIntegration: true,
            nodeintegrationinsubframes: true,
            preload: preload
        }

    };
    let mainWindow = new BrowserWindow(windowOptions);

    if (mainHtml.startsWith("http")) {
        mainWindow.loadURL(mainHtml);
    } else {
        mainWindow.loadFile(mainHtml);
    }

    //接收渲染进程的信息
    mainWindow.on('closed', () => {
        mainWindow = null
    })

    let width = plugin.pluginInfo.pluginSetting.traySetting.width
    let heigth = plugin.pluginInfo.pluginSetting.traySetting.heigth

    mainWindow.setSize(width, heigth)

    mainWindow.on('blur', () => {
        mainWindow.hide()
    })


    EnvContext.getInstance().setTrayWindow(winId, mainWindow)
}
